<template>
  <div class="coupon">
    <div class="header">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="formInline.name"
            placeholder="请输入优惠卷标题"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="formInline.type"
            placeholder="请选择优惠卷类型"
            clearable
          >
            <el-option label="通用领券" value="0"></el-option>
            <el-option label="注册赠券" value="1"></el-option>
            <el-option label="兑换码" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="formInline.status"
            placeholder="请选择优惠卷状态"
            clearable
          >
            <el-option label="正常" value="0"></el-option>
            <el-option label="已过期" value="1"></el-option>
            <el-option label="已下架" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" icon="el-icon-search"
            >查找</el-button
          >
          <el-button type="primary" @click="handleAdd" class="el-icon-edit"
            >添加</el-button
          >
          <el-button
            type="primary"
            @click="handleDaochu"
            class="el-icon-download"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="main">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="优惠卷ID" align="center">
        </el-table-column>
        <el-table-column prop="name" label="优惠卷名称" align="center">
        </el-table-column>
        <el-table-column prop="desc" label="介绍" align="center">
        </el-table-column>
        <el-table-column prop="tag" label="标签" align="center">
        </el-table-column>
        <el-table-column prop="min" label="最低消费" align="center">
          <template slot-scope="scope">
            <p>满{{ scope.row.min }}可用</p>
          </template>
        </el-table-column>
        <el-table-column prop="discount" label="满减金额" align="center">
          <template slot-scope="scope">
            <p>减免{{ scope.row.discount }}元</p>
          </template>
        </el-table-column>
        <el-table-column prop="limit" label="每人限领" align="center">
        </el-table-column>
        <el-table-column prop="goodsType" label="商品使用范围" align="center">
          <template slot-scope="scope">
            <p v-if="scope.row.goodsType == 1">指定分类</p>
            <p v-else-if="scope.row.goodsType == 0">全场通用</p>
            <p v-else>指定商品</p>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="优惠卷类型" align="center">
          <template slot-scope="scope">
            <p v-if="scope.row.type == 1">注册赠劵</p>
            <p v-else-if="scope.row.type == 0">通用领券</p>
            <p v-else>兑换码</p>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="优惠卷数量" align="center">
          <template slot-scope="scope">
            <p v-if="scope.row.total == 0">不限</p>
            <p v-else>{{ scope.row.total }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <p v-if="scope.row.status == 0">正常</p>
            <p v-else-if="scope.row.status == 1">已过期</p>
            <p v-else>已下架</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作"
          align="center"
          width="250px"
        >
          <template slot-scope="scope">
            <el-button size="mini" @click="handleView(scope.row)" type="primary"
              >详情</el-button
            >

            <el-button size="mini" @click="handleEdit(scope.row)" type="info"
              >编辑</el-button
            >

            <el-button size="mini" @click="handleDel(scope.row)" type="danger"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
    <!-- 对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      @close="cancel"
    >
      <div class="box">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="优惠卷名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="介绍">
            <el-input v-model="ruleForm.desc"></el-input>
          </el-form-item>
          <el-form-item label="标签">
            <el-input v-model="ruleForm.tag"></el-input>
          </el-form-item>
          <el-form-item label="最低消费">
            <el-input v-model="ruleForm.min">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="满额金额">
            <el-input v-model="ruleForm.discount">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="每人限领">
            <el-input v-model="ruleForm.limit">
              <template slot="append">张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="分发类型">
            <el-select v-model="ruleForm.type">
              <el-option label="通用领券" value="0"></el-option>
              <el-option label="注册赠券" value="1"></el-option>
              <el-option label="兑换码" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="优惠卷数量">
            <el-input v-model="ruleForm.total">
              <template slot="append">张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="有效期">
            <div>
              <el-radio-group v-model="ruleForm.radio">
                <el-radio-button label="领券相对天数"></el-radio-button>
                <el-radio-button label="指定绝对时间"></el-radio-button>
              </el-radio-group>
              <div class="show">
                <el-input
                  v-model="ruleForm.days"
                  v-if="ruleForm.radio === '领券相对天数'"
                >
                  <template slot="append">天</template>
                </el-input>
                <el-date-picker
                  v-if="ruleForm.radio === '指定绝对时间'"
                  v-model="ruleForm.time"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  align="right"
                >
                </el-date-picker>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="商品限制范围">
            <div>
              <el-radio-group v-model="ruleForm.goodsType">
                <el-radio-button label="全场通用" value="0"></el-radio-button>
                <el-radio-button label="指定分类" value="1"></el-radio-button>
                <el-radio-button label="指定商品" value="2"></el-radio-button>
              </el-radio-group>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm(1)" v-if="title == '创建'"
          >确 定</el-button
        >
        <el-button type="primary" @click="confirm(2)" v-if="title == '编辑'"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  listCoupon,
  createCoupon,
  updateCoupon,
  deleteCoupon,
} from "@/api/coupon.js";
import pagination from "@/components/Pagination/index.vue";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
export default {
  // 标识,当前组件的名称
  name: "coupon",
  data() {
    return {
      title: "",
      dialogVisible: false,
      total: 0,
      formInline: {
        name: null,
        type: null,
        status: null,
      },
      tableData: [],
      ruleForm: {
        name: "",
        desc: "",
        tag: "",
        min: 0,
        discount: 0,
        limit: 1,
        type: "通用领券",
        total: 0,
        radio: "领券相对天数",
        days: 0,
        time: [],
        goodsType: "全场通用",
      },
      rules: {
        name: [
          { required: true, message: "优惠券标题不能为空", trigger: "blur" },
        ],
      },
      listQuery: {
        page: 1,
        limit: 20,
        sort: "add_time",
        order: "desc",
      },
      obj: {},
    };
  },
  methods: {
    getList() {
      listCoupon(this.listQuery)
        .then((response) => {
          this.tableData = response.data.data.list;
          this.total = response.data.data.total;
        })
        .catch(() => {
          this.tableData = [];
          this.total = 0;
        });
    },
    // 导出
    handleDaochu() {
      // 创建一个workbook
      const workbook = XLSX.utils.book_new(); // 导出数据
      const worksheet = XLSX.utils.json_to_sheet(this.tableData);
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet 1"); // 将workbook转为二进制数据

      const excelData = XLSX.write(workbook, {
        type: "array",
        bookType: "xlsx",
      }); // 创建blob对象并保存excel文件
      const blob = new Blob([excelData], { type: "application/octet-stream" }); // 设置导出文件名字
      saveAs(blob, "data.xlsx");
    },
    // 查找
    onSubmit() {
      this.listQuery.name = this.formInline.name;
      this.listQuery.type = this.formInline.type;
      this.listQuery.status = this.formInline.status;
      this.getList();
    },
    // 详情
    handleView(row) {
      this.$router.push({
        path: "couponDetail",
        query: {
          id: row.id,
        },
      });
    },
    // 编辑
    handleEdit(row) {
      this.title = "编辑";
      this.dialogVisible = true;
      this.ruleForm = {
        name: row.name,
        desc: row.desc,
        tag: row.tag,
        min: row.min,
        discount: row.discount,
        limit: row.limit,
        type: "通用领券",
        total: row.total,
        radio: "领券相对天数",
        days: row.days,
        time: [],
        goodsType: "全场通用",
      };

      this.ruleForm.time[0] = row.startTime;
      this.ruleForm.time[1] = row.endTime;
      if (row.type == 0) {
        this.ruleForm.type = "通用领券";
      } else if (row.type == 1) {
        this.ruleForm.type = "注册赠券";
      } else {
        this.ruleForm.type = "兑换码";
      }
      if (row.goodsType == 0) {
        this.ruleForm.goodsType = "全场通用";
      } else if (row.goodsType == 1) {
        this.ruleForm.goodsType = "指定分类";
      } else {
        this.ruleForm.goodsType = "指定商品";
      }
      this.obj = JSON.parse(JSON.stringify(row));
    },
    // 删除
    handleDel(row) {
      deleteCoupon(row).then((response) => {
        this.$message({
          type: "success",
          message: "删除成功!",
        });
        this.getList();
      });
    },

    // 添加
    handleAdd() {
      this.title = "创建";
      // 打开模态框
      this.dialogVisible = true;
    },
    // 确定
    confirm(val) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 添加对话框接口
          if (val === 1) {
            let startTime; // 将变量声明移到外部
            let endTime; // 将变量声明移到外部
            if (this.ruleForm.time == "") {
              startTime = null;
              endTime = null;
            } else {
              startTime = this.formatDateTimeUTC(this.ruleForm.time[0]);
              endTime = this.formatDateTimeUTC(this.ruleForm.time[1]);
            }
            if (this.ruleForm.type == "通用领券") {
              this.ruleForm.type = 0;
            } else if (this.ruleForm.type == "注册赠券") {
              this.ruleForm.type = 1;
            } else {
              this.ruleForm.type = 2;
            }
            if (this.ruleForm.goodsType == "全场通用") {
              this.ruleForm.goodsType = 0;
            } else if (this.ruleForm.goodsType == "指定分类") {
              this.ruleForm.goodsType = 1;
            } else {
              this.ruleForm.goodsType = 2;
            }
            let data = {
              name: this.ruleForm.name,
              desc: this.ruleForm.desc,
              tag: this.ruleForm.tag,
              min: this.ruleForm.min,
              discount: this.ruleForm.discount,
              limit: this.ruleForm.limit,
              type: this.ruleForm.type,
              total: this.ruleForm.total,
              days: this.ruleForm.days,
              startTime: startTime,
              endTime: endTime,
              goodsType: this.ruleForm.goodsType,
            };
            createCoupon(data).then((response) => {
              this.$message({
                type: "success",
                message: "新增成功!",
              });
              this.ruleForm = {
                name: "",
                desc: "",
                tag: "",
                min: 0,
                discount: 0,
                limit: 1,
                type: "通用领券",
                total: 0,
                radio: "领券相对天数",
                days: 0,
                time: "",
                goodsType: "全场通用",
              };
              this.dialogVisible = false;
              this.getList();
            });
          }
          // 编辑对话框接口
          else {
            this.obj.name = this.ruleForm.name;
            this.obj.desc = this.ruleForm.desc;
            this.obj.tag = this.ruleForm.tag;
            this.obj.min = this.ruleForm.min;
            this.obj.discount = this.ruleForm.discount;
            this.obj.limit = this.ruleForm.limit;
            this.obj.total = this.ruleForm.total;
            this.obj.days = this.ruleForm.days;
            if (this.ruleForm.type == "0") {
              this.obj.type = 0;
            } else if (this.ruleForm.type == "1") {
              this.obj.type = 1;
            } else {
              this.obj.type = 2;
            }
            if (this.ruleForm.goodsType == "全场通用") {
              this.obj.goodsType = 0;
            } else if (this.ruleForm.goodsType == "指定分类") {
              this.obj.goodsType = 1;
            } else {
              this.obj.goodsType = 2;
            }
            updateCoupon(this.obj).then((response) => {
              this.$message({
                type: "success",
                message: "更新成功!",
              });
              this.ruleForm = {
                name: "",
                desc: "",
                tag: "",
                min: 0,
                discount: 0,
                limit: 1,
                type: "通用领券",
                total: 0,
                radio: "领券相对天数",
                days: 0,
                time: "",
                goodsType: "全场通用",
              };
              this.dialogVisible = false;
              this.getList();
            });
          }
        } else {
          return false;
        }
      });
    },
    // 取消
    cancel() {
      this.ruleForm = {
        name: "",
        desc: "",
        tag: "",
        min: 0,
        discount: 0,
        limit: 1,
        type: "通用领券",
        total: 0,
        radio: "领券相对天数",
        days: 0,
        time: "",
        goodsType: "全场通用",
      };
      this.dialogVisible = false;
    },
    // 时间格式化
    formatDateTimeUTC(dateTimeStr) {
      const date = new Date(dateTimeStr);
      if (isNaN(date)) {
        // 如果无法解析为日期，则原样返回（或抛出错误，取决于您的需求）
        return dateTimeStr;
      }
      const year = date.getUTCFullYear();
      const month = String(date.getUTCMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
      const day = String(date.getUTCDate()).padStart(2, "0");
      const hours = String(date.getUTCHours()).padStart(2, "0");
      const minutes = String(date.getUTCMinutes()).padStart(2, "0");
      const seconds = String(date.getUTCSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  },
  components: {
    pagination,
  },
  mounted() {
    this.getList();
  },
};
</script>
<style lang="scss" scoped>
@import "./scss/coupon.scss";
</style>